// 云打印系统客户端JavaScript

// DOM元素
const fileInput = document.getElementById('file-input');
const uploadForm = document.getElementById('upload-form');
const uploadArea = document.getElementById('upload-area');
const filesList = document.getElementById('files-list');
const uploadStatus = document.getElementById('upload-status');
const printModal = document.getElementById('print-modal');
const printerSelect = document.getElementById('printer-select');
const printBtn = document.getElementById('print-btn');
const startServiceBtn = document.getElementById('start-service-btn');

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 获取打印机列表
    fetchPrinters();
    
    // 获取已上传文件列表
    fetchFiles();
    
    // 初始化UI事件
    initEvents();
});

// 初始化UI事件
function initEvents() {
    // 点击上传区域触发文件选择
    if (uploadArea) {
        uploadArea.addEventListener('click', function() {
            fileInput.click();
        });
    }
    
    // 拖放文件
    if (uploadArea) {
        uploadArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            uploadArea.classList.add('border-primary');
        });
        
        uploadArea.addEventListener('dragleave', function() {
            uploadArea.classList.remove('border-primary');
        });
        
        uploadArea.addEventListener('drop', function(e) {
            e.preventDefault();
            uploadArea.classList.remove('border-primary');
            
            if (e.dataTransfer.files.length) {
                fileInput.files = e.dataTransfer.files;
                handleFileUpload();
            }
        });
    }
    
    // 文件选择变化
    if (fileInput) {
        fileInput.addEventListener('change', handleFileUpload);
    }
    
    // 表单提交
    if (uploadForm) {
        uploadForm.addEventListener('submit', function(e) {
            e.preventDefault();
            handleFileUpload();
        });
    }
    
    // 启动打印服务
    if (startServiceBtn) {
        startServiceBtn.addEventListener('click', startPrintService);
    }
}

// 获取打印机列表
async function fetchPrinters() {
    try {
        const response = await fetch('/printers');
        const data = await response.json();
        
        if (printerSelect) {
            // 清空选择框
            printerSelect.innerHTML = '';
            
            // 添加打印机选项
            data.printers.forEach(printer => {
                const option = document.createElement('option');
                option.value = printer;
                option.textContent = printer;
                
                // 设置默认打印机
                if (printer === data.default) {
                    option.selected = true;
                }
                
                printerSelect.appendChild(option);
            });
        }
    } catch (error) {
        showAlert('获取打印机列表失败: ' + error.message, 'danger');
    }
}

// 获取已上传文件列表
async function fetchFiles() {
    try {
        const response = await fetch('/files');
        const data = await response.json();
        
        if (filesList) {
            updateFilesList(data.files);
        }
    } catch (error) {
        showAlert('获取文件列表失败: ' + error.message, 'danger');
    }
}

// 更新文件列表
function updateFilesList(files) {
    if (!filesList) return;
    
    // 清空列表
    filesList.innerHTML = '';
    
    if (files.length === 0) {
        filesList.innerHTML = '<tr><td colspan="5" class="text-center">暂无上传文件</td></tr>';
        return;
    }
    
    // 添加文件项
    files.forEach(file => {
        const row = document.createElement('tr');
        
        // 格式化日期
        const uploadDate = new Date(file.upload_time);
        const formattedDate = uploadDate.toLocaleString('zh-CN');
        
        // 格式化文件大小
        const fileSize = formatFileSize(file.size);
        
        // 设置状态标记颜色
        let statusClass = 'status-default';
        let statusText = '已上传';
        
        if (file.status === 'queued') {
            statusClass = 'status-warning';
            statusText = '队列中';
        } else if (file.status === 'printing') {
            statusClass = 'status-primary';
            statusText = '打印中';
        } else if (file.status === 'printed') {
            statusClass = 'status-success';
            statusText = '已打印';
        } else if (file.status === 'error') {
            statusClass = 'status-danger';
            statusText = '错误';
        }
        
        row.innerHTML = `
            <td>${file.original_filename}</td>
            <td>${fileSize}</td>
            <td>${formattedDate}</td>
            <td><span class="status-indicator ${statusClass}"></span>${statusText}</td>
            <td>
                <button class="btn btn-sm btn-primary print-btn" data-filename="${file.saved_filename}">打印</button>
            </td>
        `;
        
        filesList.appendChild(row);
        
        // 添加打印按钮点击事件
        const printButtons = row.querySelectorAll('.print-btn');
        printButtons.forEach(btn => {
            btn.addEventListener('click', function() {
                openPrintModal(btn.dataset.filename);
            });
        });
    });
}

// 处理文件上传
async function handleFileUpload() {
    if (!fileInput || !fileInput.files.length) return;
    
    const file = fileInput.files[0];
    const formData = new FormData();
    formData.append('file', file);
    
    try {
        // 显示上传状态
        if (uploadStatus) {
            uploadStatus.innerHTML = '上传中...';
            uploadStatus.className = 'alert alert-info';
            uploadStatus.style.display = 'block';
        }
        
        const response = await fetch('/upload', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (!response.ok) {
            throw new Error(result.detail || '上传失败');
        }
        
        // 显示成功消息
        if (uploadStatus) {
            uploadStatus.innerHTML = '文件上传成功';
            uploadStatus.className = 'alert alert-success';
        }
        
        // 清空文件输入
        fileInput.value = '';
        
        // 刷新文件列表
        fetchFiles();
        
    } catch (error) {
        // 显示错误消息
        if (uploadStatus) {
            uploadStatus.innerHTML = '上传失败: ' + error.message;
            uploadStatus.className = 'alert alert-danger';
        }
    }
}

// 打开打印对话框
function openPrintModal(filename) {
    if (!printModal) return;
    
    // 存储文件名
    printModal.dataset.filename = filename;
    
    // 显示对话框
    printModal.classList.add('show');
    
    // 添加打印按钮事件
    if (printBtn) {
        printBtn.onclick = function() {
            printFile(filename);
        };
    }
    
    // 添加关闭按钮事件
    const closeButtons = printModal.querySelectorAll('.close, .cancel-btn');
    closeButtons.forEach(btn => {
        btn.onclick = function() {
            printModal.classList.remove('show');
        };
    });
}

// 打印文件
async function printFile(filename) {
    if (!filename) return;
    
    try {
        // 获取选择的打印机
        const printer = printerSelect ? printerSelect.value : '';
        
        const response = await fetch('/print_file', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                filename: filename,
                printer: printer
            })
        });
        
        const result = await response.json();
        
        if (!response.ok) {
            throw new Error(result.detail || '打印失败');
        }
        
        // 关闭对话框
        if (printModal) {
            printModal.classList.remove('show');
        }
        
        // 显示成功消息
        showAlert('文件已加入打印队列', 'success');
        
        // 刷新文件列表
        fetchFiles();
        
    } catch (error) {
        showAlert('打印失败: ' + error.message, 'danger');
    }
}

// 启动打印服务
async function startPrintService() {
    try {
        const response = await fetch('/start_print_service', {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (result.status === 'success') {
            showAlert('打印服务已启动', 'success');
        } else {
            throw new Error(result.message || '启动失败');
        }
        
    } catch (error) {
        showAlert('启动打印服务失败: ' + error.message, 'danger');
    }
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 显示警告/提示信息
function showAlert(message, type = 'info') {
    // 创建弹出提示
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible`;
    alertDiv.style.position = 'fixed';
    alertDiv.style.top = '20px';
    alertDiv.style.right = '20px';
    alertDiv.style.zIndex = '9999';
    alertDiv.style.maxWidth = '400px';
    
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="close" onclick="this.parentElement.remove();">&times;</button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // 3秒后自动消失
    setTimeout(() => {
        alertDiv.remove();
    }, 3000);
} 